package index;

import java.io.IOException;
import java.util.Iterator;

import net.barashev.seclub.io.BufferManager;
import net.barashev.seclub.io.DataMarshaller;
import net.barashev.seclub.io.IteratingSlot;
import net.barashev.seclub.io.file.VFile;

public class VFileIterator<T> implements Iterator<T> {

    private IteratingSlot<T, DataMarshaller<T>> slot;
    private int idxRecord;
    private boolean slotNotEnd;

    public VFileIterator(VFile<T> file, BufferManager bufferMgr) {
        VFileIterator(file, bufferMgr,1);
    }

    public VFileIterator(VFile<T> file, BufferManager bufferMgr, int bufferCount) {
        VFileIterator(file, bufferMgr,bufferCount);
    }

    private void VFileIterator(VFile<T> file, BufferManager bufferMgr, int bufferCount) {
        slot = bufferMgr.allocateIteratingSlot(bufferCount, file);
        idxRecord  = 0;
        //if file is not Empty
        slotNotEnd = true;
    }

    @Override
    public boolean hasNext() {
        if (idxRecord == slot.getRecordCount()) {
            try {
                if (slot.pull()) {
                    idxRecord = 0;
                }else {
                    slotNotEnd = false;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return slotNotEnd;
    }

    @Override
    public T next() {
        T fileElement = slot.getBlock(0).get(idxRecord);
        idxRecord++;
        return fileElement;
    }

    @Override
    public void remove() {
        // TODO Auto-generated method stub

    }

}
